package cn.zebra.dev.admin.module.order.controller;

import cn.zebra.dev.admin.module.order.dto.OrderItemDTO;
import cn.zebra.dev.admin.module.order.dto.VirtualOrdersListDTO;
import cn.zebra.dev.common.restful.Result;
import cn.zebra.dev.ibatis.plus.utils.PageUtils;
import cn.zebra.dev.order.module.item.entity.OrdersItemEntity;
import cn.zebra.dev.order.module.item.service.OrdersItemService;
import cn.zebra.dev.order.module.order.constant.OrdersTypeConstant;
import cn.zebra.dev.order.module.order.entity.OrdersEntity;
import cn.zebra.dev.order.module.order.service.OrdersService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@Api(tags = "虚拟物品订单")
@RequestMapping("/orderVirtual")
public class VirtualOrderController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrdersItemService ordersItemService;

    @GetMapping("/list")
    @ApiOperation("虚拟物品订单列表")
    public Result<PageUtils<VirtualOrdersListDTO>> list(
            @RequestParam(value = "limit", defaultValue = "10", required = false) Integer limit,
            @RequestParam(value = "page", defaultValue = "1", required = false) Integer page) {
        Map<String, Object> map = new HashMap<>();
        map.put("limit", limit);
        map.put("page", page);
        map.put("ordersType", OrdersTypeConstant.VIRTUAL);
        PageUtils<OrdersEntity> pageUtils = ordersService.findPage(map);
        PageUtils<VirtualOrdersListDTO> data = new PageUtils<>(pageUtils);
        List<OrdersEntity> list = pageUtils.getList();
        List<VirtualOrdersListDTO> dtoList = new LinkedList<>();
        list.forEach(entity -> {
            VirtualOrdersListDTO dto = new VirtualOrdersListDTO();
            BeanUtils.copyProperties(entity, dto);
            dtoList.add(dto);
        });
        data.setList(dtoList);
        return Result.success(data);
    }

    @GetMapping("/info/{id}")
    @ApiOperation("虚拟订单详情")
    public Result<VirtualOrdersListDTO> info(@PathVariable Long id) {
        OrdersEntity entity = ordersService.findById(id);
        if (entity == null) {
            return Result.error("没有此订单");
        }
        VirtualOrdersListDTO dto = new VirtualOrdersListDTO();
        BeanUtils.copyProperties(entity, dto);
        //通过订单表id得到订单明细表
        Collection<OrdersItemEntity> itemEntities = ordersItemService.findByOrderId(entity.getId());
        List<OrderItemDTO> itemList = new ArrayList<>(itemEntities.size());
        itemEntities.forEach(itemEntity -> {
            OrderItemDTO itemDTO = new OrderItemDTO();
            BeanUtils.copyProperties(itemEntity, itemDTO);
            itemList.add(itemDTO);
        });
        dto.setItemList(itemList);
        return Result.success(dto);
    }

}
